<template>
	<!-- 	style="height: 7400rpx;background-image: url('https://yun.shlxkj.info:44300/%E9%97%B5%E8%A1%8C%E7%96%BE%E6%8E%A7%E5%85%8D%E8%B4%B9%E5%92%A8%E8%AF%A2%E9%A1%B9%E7%9B%AE/%E5%89%8D%E7%AB%AF%E5%9B%BE%E7%89%87/%E9%97%AE%E5%8D%B7%E8%B0%83%E6%9F%A5%E8%83%8C%E6%99%AF%E5%9B%BE.jpg');background-size: 100% 100%;background-repeat: no-repeat;" -->
	<view>
		<!-- 问卷显示 -->
		<view v-if="wenjuanHide">
			<view class="bg-img-box">
				<view v-for="(item,index) in processArrdata" :key="item.id">
					<!-- 题目 -->
					<view class="radio-title-text">
						<text v-if="item.necessarily" class="red-text">*</text>
						{{item.codenum}}：{{item.text}}
					</view>
					<!-- 单选题 -->
					<view v-if="item.qtype==1">
						<radio-group @change="radioChange($event,item)">
							<label class="radio-item" v-for="(params, num) in item.options" :key="item.id"
								style="margin-bottom: 10rpx;">
								<view class="radio-group-flex">
									<view>
										<radio :value="params.id" :checked="params.checked" color='#007AFF' />
									</view>
									<view class="radio-text">{{params.option}}</view>
								</view>
							</label>
						</radio-group>
					</view>
					<!-- 多选题 -->
					<view v-if="item.qtype==2">
						<checkbox-group @change="checkboxChange($event,item)">
							<label v-for="(params, num) in item.options" :key="item.id" class="checkbox-box">
								<checkbox :value="params.id" :checked="false" color='#007AFF' />{{params.option}}
							</label>
						</checkbox-group>
					</view>
					<!-- 自定义输入 -->
					<view v-if="item.qtype==3">
						<view>
							<!-- <input class="custom-input" placeholder="请输入" :value="inputClearValue"
							@input="pureInput($event,index,item)" /> -->
							<uni-easyinput v-if="item.id!=67&&item.id!=68" v-model="item.inputText" placeholder="注明请输入"
								@input="pureInput($event,index,item)"></uni-easyinput>
							<uni-easyinput v-if="item.id==67||item.id==68" v-model="item.inputText"
								placeholder="由系统自动生成" @input="pureInput($event,index,item)"
								disabled="true"></uni-easyinput>

						</view>
					</view>
					<!-- 单选题自定义 -->
					<view v-if="item.qtype==4">
						<radio-group @change="radioChange($event,item)">
							<label class="radio-item" v-for="(params, num) in item.options" :key="item.id"
								style="margin-bottom: 10rpx;">
								<view class="radio-group-flex">
									<view>
										<radio :value="params.id" :checked="false" color='#007AFF' />
									</view>
									<view class="radio-text">{{params.option}}</view>
								</view>
							</label>
						</radio-group>
						<!-- <input class="custom-input" placeholder="注明请输入" :value="item.inputText"
						@input="pureInput($event,index,item)" /> -->

						<uni-easyinput v-model="item.inputText" placeholder="注明请输入"
							@input="pureInput($event,index,item)"></uni-easyinput>

					</view>
					<!-- 多选题自定义 -->
					<view v-if="item.qtype==5">
						<checkbox-group @change="checkboxChange($event,item)">
							<label v-for="(params, num) in item.options" :key="item.id" class="checkbox-box">
								<checkbox :value="params.id" :checked="params.checked" color='#007AFF' />
								{{params.option}}
							</label>
						</checkbox-group>
						<uni-easyinput v-model="item.inputText" placeholder="注明请输入"
							@input="pureInput($event,index,item)"></uni-easyinput>
					</view>
				</view>
				<view class="button-box">
					<button v-if="buttonHide" style="background-color: #007AFF;color: #FFF;margin-bottom: 30rpx;"
						@click="NextPage">下一页</button>
					<!-- <button v-if="(!buttonHide)&&(!disabledType)" style="background-color: #007AFF;color: #FFF;"
						@click="subEven" :disabled='disabledType'>提交</button> -->
					<button v-if="!buttonHide" style="background-color: #007AFF;color: #FFF;margin-bottom: 30rpx;"
						@click="subEvens">下一步</button>
				</view>
			</view>
		</view>


	</view>
</template>

<script>
	import {
		NanCangGetQuestionnaireAsync,
		// getVerifyNumber,
		// CreateAndForwardMax3sAsync,
		// GetQuestionnaireByPhone,
		// SetDeviceNoAndForwardMax3sAsync
	} from '@/utils/api.js'
	import {
		debounce
	} from '@/utils/util.js';
	export default {
		data() {
			return {
				jumpClickType: false,
				arrayData: [],
				current: 1,
				inputClearValue: "",
				processArrdata: [],
				sliceValue: 0,
				answerArr: [],
				backupsliceValue: 0,
				buttonHide: true,
				// lengthArr:0,
				phone: null,
				wenjuanHide: true,
				completeHide: false,
				deviceNumber: null,
				disabledType: false,
				referrerCode: 0, //推荐人编码
				referrerHide: true,
			}
		},
		// onLoad(query) {

		// 	const data = uni.getStorageSync('lifeData');
		// 	if (data) {
		// 		this.phone = data.vx_u_info.phone
		// 	}
		// 	// this.getData()
		// 	this.getQuest()
		// },

		// 组件（Component）只能使用 created、mounted、beforeDestroy 等 Vue 标准生命周期
		created() {
			// const data = uni.getStorageSync('lifeData');
			// if (data) {
			// 	this.phone = data.vx_u_info.phone
			// }
			// this.getData()
			this.getQuest()
		},
		methods: {
			async getQuest() {
				const res = await NanCangGetQuestionnaireAsync(2)
				//第一页数据
				if (res.code == 200) {
					res.data.sort((a, b) => a.codenum - b.codenum)
					let jumpType = true
					res.data.forEach((element, index) => {
						element.options.forEach(elementTwo => {
							if (elementTwo.skip) {
								jumpType = false
							}
							//外层增加一个输入框绑定字段
							if (elementTwo.handfill) {
								element['inputText'] = ''
							}
						})

						//判断多选框注明字段
						if (element.qtype == 5) {
							// 外层增加注明字段
							element.specify = false
						}


						if (jumpType) {
							this.sliceValue = index + 2
							this.backupsliceValue = this.sliceValue
							console.log(index);
						}
					})
					console.log(res.data.sort((a, b) => a.codenum - b.codenum), '排序完的数据');
					this.arrayData = res.data.sort((a, b) => a.codenum - b.codenum)
					this.processArrdata = this.arrayData.slice(0, this.sliceValue)

					console.log(this.processArrdata, '第一次截取数组');
				}
			},

			//下一页数据
			async NextPage() {
				let mandatoryJump = true
				//判断必选题是否没有做

				console.log(this.processArrdata, '页面展示数据111');

				this.arrayData.forEach((elementFather, FatherIndex) => {
					this.processArrdata.forEach((element, index) => {
						if (elementFather.id == element.id) {
							//必选题
							if (element.necessarily) {
								// console.log(this.answerArr[FatherIndex],'当前答案题目');
								//必选题没有做
								if (this.answerArr[FatherIndex] == null) {

									console.log(elementFather.text, '必选题没有做');
									//false必选题没有做
									mandatoryJump = false
									uni.showToast({
										icon: 'none',
										title: '请完成带红色星号的题目'
									})

								} else {
									let arrNum = this.answerArr[FatherIndex].optionIds.length
									//必选题没有做
									if (arrNum == 0) {
										console.log(elementFather.text, '必选题没有做2');
										//false必选题没有做
										mandatoryJump = false
										uni.showToast({
											icon: 'none',
											title: '请完成带红色星号的题目'
										})

									}
								}

								// console.log(this.answerArr[FatherIndex], '必选题答案');
							}
						}


					})

				})

				console.log(this.answerArr, '选中的答案');

				//必选题都做了
				if (mandatoryJump) {

					//判断推荐码是否正确
					// if (this.referrerHide) {
					// 	const res = await getVerifyNumber(this.referrerCode)
					// 	if (res.data) {
					// 		this.referrerHide = false
					// 	} else {
					// 		uni.showToast({
					// 			icon: 'none',
					// 			title: '推荐人编码不正确'
					// 		})
					// 		//方法中断
					// 		return
					// 	}
					// }


					console.log('方法中断');

					this.processArrdata = []
					// + 1
					console.log(this.sliceValue, '下一步开始截取值');

					// if(){

					// }
					let sliceArr = []
					// if (this.jumpClickType) {
					// 	console.log('执行1判断');
					// 	sliceArr = this.arrayData.slice(this.sliceValue)
					// } else {
					// 	console.log('执行2判断');
					// 	sliceArr = this.arrayData.slice(this.sliceValue + 1)
					// }
					let onceType = true
					sliceArr = this.arrayData.slice(this.sliceValue)
					console.log(sliceArr, '剩下的值');
					let jumpType = true
					let xunID = null
					let num = 1
					let pushValue = true //判断是否追加过，有错误不追加，没有错误追加
					try {
						sliceArr.forEach((element, index) => {
							element.options.forEach(elementTwo => {
								if (elementTwo.skip) {
									jumpType = false
								}

							})
							if (jumpType) {
								console.log('寻找id执行了');
								num++
								xunID = element.id
								pushValue = false
							}

							//跳转时当前第一题就是跳转题执行
							// if (pushValue) {
							// 	num++
							// 	console.log('跳转时当前第一题就是跳转题执行');
							// 	xunID = element.id
							// }
						})
					} catch (e) {

					}
					this.processArrdata = sliceArr.slice(0, num)

					//控制按钮显示(-10页面结束)
					this.processArrdata.forEach(element => {
						if (element.end == -10) {
							this.buttonHide = false
							console.log('提交按钮111');
						}

					})

					//寻找截取到id多少
					this.arrayData.forEach((element, index) => {
						if (element.id == xunID) {
							onceType = false
							this.sliceValue = index + 2
							this.backupsliceValue = this.sliceValue
							console.log(this.sliceValue, '下一步结束的截取值');
						}
					})
					//跳转不执行的时追加
					if (onceType) {
						console.log('跳转不执行的时追加');
						this.sliceValue = this.sliceValue + 1
						this.backupsliceValue = this.sliceValue
					}


				}

				console.log(this.processArrdata, '页面展示数据222');
			},
			//单选框操作
			radioChange(even, params) {
				// even.detail.value
				let jump = false
				let answerData = ''
				let sliceNum = null
				let sliceJump = false
				let isOther = true
				let sliceValuebackup = null

				let isTypeData = false
				//判断题目是否为跳转题
				if (params.skiped) {
					console.log('点击跳转题了');
					isTypeData = true
				}

				console.log(even.detail.value, '单选框选择数据');
				this.arrayData.forEach((element, index) => {
					element.options.forEach(elementTwo => {
						if (elementTwo.id == even.detail.value) {
							// console.log(elementTwo, '执行111');

							//页面题目中出现-5,出现提交按钮
							if (elementTwo.end == -5) {
								// console.log('提交按钮');
								this.buttonHide = false
							}

							// else {
							// 	// console.log('显示下一步按钮');
							// 	this.buttonHide = true
							// }


							if (elementTwo.handfill) {
								isOther = false
								let arr = []
								let data = {
									question: element.text,
									optionIds: arr
								}
								this.answerArr[index] = data
								//重置选择框数据
								// this.processArrdata[3].inputText = ''
								// 清空第 3 项的 inputText
								this.$set(this.processArrdata[3], 'inputText', '');
								console.log(this.processArrdata, '关联输入框数据');
								console.log(this.answerArr, '单选框自定义答案');
							}
							jump = true
							answerData = elementTwo.option
							//判断下一步是否是跳转页面
							if (elementTwo.nextquestionid != 0) {

								console.log('执行222');
								this.arrayData.forEach((params, pasindex) => {
									if (elementTwo.nextquestionid == params.id) {
										sliceJump = true
										sliceNum = pasindex
									}
								})
							} else {

								console.log('执行333');
								sliceJump = false
							}
						}
					})
					//取到选项最外层数据对象

					if (jump && isOther) {
						let arr = []
						arr.push(answerData)
						let data = {
							question: element.text,
							optionIds: arr
						}
						this.answerArr[index] = data
						jump = false
					}
				})
				
				if (isTypeData) { //执行跳转页面赋值
					if (sliceJump) {
						this.jumpClickType = true
						this.sliceValue = sliceNum
					} else {
						//复原选项数据
						this.sliceValue = this.backupsliceValue
					}
				} //执行跳转页面赋值



				console.log(this.sliceValue, '执行跳转页面赋值');
				console.log(this.answerArr, '单选框答案');
			},
			//纯输入框
			pureInput(even, index, item) {
				console.log(even);
				console.log(index);
				console.log(item);

				if (item.id == 111) {
					this.referrerCode = even
				}

				//不是多选题注明
				if (item.qtype != 5) {
					console.log('走这');
					let num = null
					this.arrayData.forEach((element, index) => {
						if (element.id == item.id) {
							num = index
						}
					})

					let arr = []
					if (even != '') {
						arr.push(even)
					}

					let data = {
						question: item.text,
						optionIds: arr
					}
					console.log(num, '对应下标');
					this.answerArr[num] = data
				} else {
					console.log('走这111');
					if (item.specify) {
						let legNum = null
						let num = null
						this.arrayData.forEach((element, index) => {
							if (element.id == item.id) {
								legNum = this.answerArr[index].optionIds.length
								console.log(legNum, '整体数组长度');
								console.log(this.answerArr[index], '数据111');
								num = index

								// console.log(num,'对应下标');
							}
						})

						this.answerArr[num].optionIds[legNum - 1] = even
					}
				}

				console.log(this.answerArr, '纯输入框');
			},
			//多选题自定义
			checkboxChange(even, item) {
				console.log(even, '多选题');
				console.log(item, '多选题22');
				// console.log(even, '多选题');
				// 				console.log(item, '多选题22');
				let choiceArr = even.detail.value
				let arrData = []
				let subscriptIndex = null
				let specifyType = false //默认未注明操作
				//取数组下标数据
				try {
					this.arrayData.forEach((element, index) => {
						if (element.id == item.id) {
							//主动退出
							subscriptIndex = index
							throw Error();
						}
					})
				} catch (err) {

				}



				//选择数据追加
				if (choiceArr.length != 0) {
					choiceArr.forEach(element => {
						item.options.forEach(params => {
							if (element == params.id) {
								if (!params.handfill) {
									arrData.push(params.option)
								} else {
									specifyType = true
									console.log('选择了注明选项');
								}
							}
						})
					})




					let data = {
						question: item.text,
						optionIds: arrData,
					}
					this.answerArr[subscriptIndex] = data
				} else {
					let data = {
						question: item.text,
						optionIds: [],
					}
					this.answerArr[subscriptIndex] = data
				}


				//选择了注明操作
				if (specifyType) {
					let daAnData = this.arrayData[subscriptIndex].inputText
					this.answerArr[subscriptIndex].optionIds.push(daAnData)
					console.log(this.answerArr, '注明操作');

					this.arrayData[subscriptIndex].specify = true
					// console.log(this.arrayData[subscriptIndex],'注明输入框答案');
				} else {
					this.arrayData[subscriptIndex].specify = false
				}


				console.log(this.answerArr, '多选题答案');
			},
			//隐藏按钮
			subEvens() {
				let mandatoryJump = true
				//判断必选题是否没有做
				this.arrayData.forEach((elementFather, FatherIndex) => {
					this.processArrdata.forEach((element, index) => {
						if (elementFather.id == element.id) {
							//必选题
							if (element.necessarily) {
								console.log(this.answerArr[FatherIndex], '当前答案题目');
								//必选题没有做
								if (this.answerArr[FatherIndex] == null) {
									//false必选题没有做
									mandatoryJump = false
									uni.showToast({
										icon: 'none',
										title: '请完成带红色星号的题目'
									})

								} else {
									let arrNum = this.answerArr[FatherIndex].optionIds.length
									//必选题没有做
									if (arrNum == 0) {
										//false必选题没有做
										mandatoryJump = false
										uni.showToast({
											icon: 'none',
											title: '请完成带红色星号的题目'
										})

									}
								}


							}
						}


					})

				})

				// if (mandatoryJump) {
				// 	this.disabledType = true
				// 	uni.showLoading({
				// 		title: '提交中...',
				// 		mask: true,
				// 	});
				// 	this.handleClick()
				// }

				//答案赋值
				this.arrayData.forEach((element, index) => {
					console.log(this.answerArr[index]);
					if (this.answerArr[index] == null) {
						let data = {
							question: element.text,
							optionIds: [],
						}

						this.answerArr[index] = data
					}
				})

				let dataForm = {
					phone: '',
					items: this.answerArr,
					// referrerCode: this.referrerCode
				}


				if (mandatoryJump) {
					console.log('传值点击了');
					this.$emit('subWenjuanEven', dataForm)
				}

			},

			// 防抖包装后的方法（注意：不能直接在模板中写 debounce(submit)，需提前绑定）
			handleClick: debounce(function() {
				console.log('防抖1111');
				this.submitEven();
			}, 2000),
			//数据提交
			async submitEven() {
				console.log('防抖成功');
				let jumpType = false
				// let dataForm = []
				this.arrayData.forEach((element, index) => {
					console.log(this.answerArr[index]);
					if (this.answerArr[index] == null) {
						let data = {
							question: element.text,
							optionIds: [],
						}

						this.answerArr[index] = data
					}
				})


				//判断是否'请收下防艾小礼品一份'
				this.answerArr.forEach(element => {
					if (element.question == '最近一年，你与异性性伴发生性行为时使用安全套的频率如何？') {
						console.log('提交执行了');
						let text = element.optionIds[0]
						console.log(text, '判断数据');
						if (text == '从未使用' || text == '有时使用') {
							jumpType = true
						}
					}


					if (element.question == '最近一年，你与同性发生过肛交性行为吗？') {
						console.log('提交执行了');
						let text = element.optionIds[0]
						console.log(text, '判断数据');
						if (text == '是') {
							jumpType = true
						}
					}
				})


				let dataForm = {
					// phone: this.phone,
					items: this.answerArr
				}

				console.log(this.answerArr, '最终答案');



				const res = await CreateAndForwardMax3sAsync(dataForm)
				if (res.code == 200) {
					if (jumpType) {
						uni.hideLoading()
						uni.showModal({
							title: '提示',
							content: '请收下防艾小礼品一份',
							showCancel: false,
							success: function(res) {
								if (res.confirm) {
									uni.reLaunch({
										url: '/pages/welcome/index'
									});
								}
							}
						});
					} else {
						uni.hideLoading()
						uni.showModal({
							title: '提示',
							content: '谢谢您的参与',
							showCancel: false,
							success: function(res) {
								if (res.confirm) {
									uni.reLaunch({
										url: '/pages/welcome/index'
									});
								}
							}
						});
					}

				} else {
					uni.hideLoading()
					this.disabledType = false
					uni.showToast({
						title: res.message,
						duration: 2000,
						icon: 'none'
					});
				}
			},

			//判断是否填写过问卷
			async getData() {
				let dataForm = {
					phone: this.phone,
				}
				const res = await GetQuestionnaireByPhone(dataForm)


				if (res.code == 200) {
					this.completeHide = true
				} else if (res.code == 801) {
					this.wenjuanHide = true
					this.getQuest()
				} else if (res.code == 802) {
					uni.showModal({
						title: '提示',
						content: '已绑定设备号：' + res.data.deviceno,
						showCancel: false,
						success: function(res) {
							if (res.confirm) {
								uni.reLaunch({
									url: '/pages/welcome/index'
								});
							}
						}
					});
				} else {
					uni.showToast({
						title: res.message,
						duration: 2000,
						icon: 'none'
					});
				}
			},

			//问卷绑定
			bindDevice() {
				// 允许从相机和相册扫码
				uni.scanCode({
					success: (res) => {
						console.log(res, '扫码结果');
						let arrData = res.result.split(',')
						let arrNum = arrData.length
						console.log(arrData, '扫码结果');
						console.log(arrData, '扫码数量');

						if (arrNum == 1) {
							let strJump = arrData[0].slice(0, 5)
							console.log(strJump, '字符串数字');
							//二码合一设备
							if (strJump == 'https') {
								let params = this.parseUrlParams(arrData[0])
								console.log(params, '二码合一');
								this.deviceNumber = params.deviceNumber
							} else {
								//盒子二维码（类似安心检测盒）
								this.deviceNumber = arrData[0]
							}

						} else if (arrNum == 2) {
							this.deviceNumber = arrData[1]
						} else {
							uni.showToast({
								icon: 'none',
								title: '该二维码格式不正确',
								duration: 2000
							})
						}
						//绑定设备号
						this.SetDevice()
						console.log(this.deviceNumber, '设备号');
					}
				});
			},

			//绑定设备号
			async SetDevice() {
				let dataForm = {
					// phone: this.phone,
					deviceno: this.deviceNumber
				}
				const res = await SetDeviceNoAndForwardMax3sAsync(dataForm)
				if (res.code == 200) {
					uni.showModal({
						title: '提示',
						content: '设备绑定成功',
						showCancel: false,
						success: function(res) {
							if (res.confirm) {
								uni.reLaunch({
									url: '/pages/welcome/index'
								});
							}
						}
					});
				} else {
					uni.showToast({
						title: res.message,
						duration: 2000,
						icon: 'none'
					})
				}
			},

			//解析url字符串
			parseUrlParams(url) {
				// 1. 提取 ? 后面的部分
				const idx = url.indexOf('?');
				if (idx === -1) return {};

				const queryStr = url.substring(idx + 1);
				const params = {};

				// 2. 按 & 分割
				const pairs = queryStr.split('&');
				for (let pair of pairs) {
					if (!pair) continue;

					// 3. 按 = 分割 key 和 value
					const eqIdx = pair.indexOf('=');
					let key, value;
					if (eqIdx === -1) {
						key = decodeURIComponent(pair);
						value = '';
					} else {
						key = decodeURIComponent(pair.substring(0, eqIdx));
						value = decodeURIComponent(pair.substring(eqIdx + 1));
					}
					params[key] = value;
				}

				return params;
			}

		}
	}
</script>

<style lang="scss" scoped>
	.flex-center-box {
		display: flex;
		justify-content: center;
		// padding-top: 50rpx;
	}

	.bg-img-box {
		// padding: 90rpx 50rpx 470rpx 50rpx;
		// margin-top: -60rpx;
		// background-image: url('https://yun.shlxkj.info:44300/%E8%89%BE%E7%91%9E%E6%B5%8B/%E5%B0%8F%E7%A8%8B%E5%BA%8F/static/img/issue.png');
		// background-size: 100% 100%;
		// background-repeat: no-repeat;
		width: 100%;
		height: 100%;
		// padding: 20rpx 30rpx;
	}

	.radio-item {
		display: inline-block;
	}

	.radio-group-flex {
		display: flex;
		// gap: 20rpx;
	}

	.radio-text {
		margin-right: 30rpx;
	}



	.checkbox-box {
		display: inline-block;
		margin: 10rpx 10rpx 10rpx 0;
	}

	.custom-input {
		border: 1px solid #ddd;
		background-color: #ffffff;
		padding: 8px 12px;
		border-radius: 6px;
		outline: none;
		/* 去除聚焦时的默认外框 */
		transition: border 0.3s;
		/* 边框颜色过渡效果 */
	}

	.button-box {
		margin-top: 60rpx;
	}

	.radio-title-text {
		margin: 15rpx 0;
		font-weight: bold;
		color: #333;
	}

	.flex-center-img-box {
		display: flex;
		flex-direction: column;
		// justify-content: center;
		align-items: center;
		margin-top: 180rpx;
	}

	.wenjuan-text {
		color: #007AFF;
		font-weight: bold;
		margin-top: 50rpx;
		font-size: 36rpx;
	}

	.pos-button-box {
		margin-top: 230rpx;
		display: flex;
		justify-content: center;
	}

	.red-text {
		color: red;
	}
</style>